package org.edu.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;
import org.edu.dao.PurviewTreeNodeDao;
import org.edu.dao.RoleDao;
import org.edu.model.Purview;
import org.edu.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(rollbackFor = { RuntimeException.class }, propagation = Propagation.REQUIRED)
public class RoleService extends ServiceAdapter<Role, String>{
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PurviewTreeNodeDao purviewTreeNodeDao;

	private static final Logger logger = Logger.getLogger(RoleService.class);
	@Override
	public void save(Role object) {
		// TODO Auto-generated method stub
		roleDao.save(object);
	}

	@Override
	public void update(Role object) {
		// TODO Auto-generated method stub
		roleDao.update(object);
	}

	@Override
	public void delete(String id) {
		// TODO Auto-generated method stub
		roleDao.delete(roleDao.get(id));
	}

	@Override
	public Role show(String id) {
		// TODO Auto-generated method stub
		return roleDao.get(id);
	}

	@Override
	public List<Role> list() {
		// TODO Auto-generated method stub
		return roleDao.loadAll();
	}
	
	/**
	 *  修改 角色的权限
	 * @param str
	 * @param roleid
	 */
	public void update(String str,String roleid) {
		
		Set<Purview> allpurview = new HashSet<Purview>();
		StringTokenizer tokenizer = new StringTokenizer(str, ",");
		
		while (tokenizer.hasMoreElements()) {
			allpurview.add(purviewTreeNodeDao.get(Integer.parseInt(tokenizer.nextElement().toString().trim())));
		}
		Role r=roleDao.get(roleid);

		r.setPurview(allpurview);
		roleDao.update(r);
		logger.info("修改完成");
	}
	/**
	 * 新建角色 返回新建角色的id
	 * @param name
	 * @return
	 */
	public String addRole(String name){
		Role r= new Role();
		r.setName(name);
		this.save(r);
		return r.getId();
	}
	/**
	 * 修改角色的 name
	 * @param name
	 * @param id
	 */
	public void updataName(String name,String id){
		Role r= roleDao.get(id);
		r.setName(name);
		this.update(r);
	}

}
